using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;

namespace Lzfy_His_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;
        private readonly ICaptchaService _captchaService;

        public AuthController(IAuthService authService, ICaptchaService captchaService)
        {
            _authService = authService;
            _captchaService = captchaService;
        }

        /// <summary>
        /// 获取验证码图片（Base64格式）
        /// </summary>
        /// <returns>验证码图片的Base64字符串和会话ID</returns>
        [HttpGet("captcha")]
        public async Task<ActionResult> GetCaptcha()
        {
            try
            {
                // 生成唯一的会话ID
                var sessionId = Guid.NewGuid().ToString();
                
                var captchaImage = await _captchaService.GenerateCaptchaAsync(sessionId);
                return Ok(new { 
                    image = captchaImage,
                    sessionId = sessionId 
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Generate captcha failed: {ex.Message}");
                return StatusCode(500, new { message = "生成验证码失败" });
            }
        }

        /// <summary>
        /// 获取验证码图片（直接返回图片文件）
        /// </summary>
        /// <returns>验证码图片文件和会话ID（通过Header返回）</returns>
        [HttpGet("captcha/image")]
        public async Task<ActionResult> GetCaptchaImage()
        {
            try
            {
                // 生成唯一的会话ID
                var sessionId = Guid.NewGuid().ToString();
                
                var captchaImageBytes = await _captchaService.GenerateCaptchaImageBytesAsync(sessionId);
                
                // 通过响应头返回会话ID
                Response.Headers["X-Session-Id"] = sessionId;
                Response.Headers["Access-Control-Expose-Headers"] = "X-Session-Id";
                
                return File(captchaImageBytes, "image/png");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Generate captcha image failed: {ex.Message}");
                return StatusCode(500, new { message = "生成验证码失败" });
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">登录请求</param>
        /// <returns>登录响应，包含JWT Token</returns>
        [HttpPost("login")]
        public async Task<ActionResult<LoginResponse>> Login([FromBody] LoginRequest request)
        {
            Console.WriteLine($"Login attempt - Username: {request?.Username}, Password: {request?.Password}, Captcha: {request?.Captcha}");
            
            if (request == null || string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                Console.WriteLine("Login failed - Empty username or password");
                return BadRequest(new { message = "用户名和密码不能为空" });
            }

            if (string.IsNullOrEmpty(request.Captcha))
            {
                Console.WriteLine("Login failed - Empty captcha");
                return BadRequest(new { message = "验证码不能为空" });
            }

            // 从请求头或查询参数获取sessionId
            var sessionId = Request.Headers["X-Session-Id"].FirstOrDefault() ?? 
                           Request.Query["sessionId"].FirstOrDefault();
            
            if (string.IsNullOrEmpty(sessionId))
            {
                Console.WriteLine("Login failed - Missing session ID");
                return BadRequest(new { message = "缺少会话ID" });
            }

            // 验证验证码
            var isCaptchaValid = await _captchaService.ValidateCaptchaAsync(sessionId, request.Captcha);
            if (!isCaptchaValid)
            {
                Console.WriteLine("Login failed - Invalid captcha");
                return BadRequest(new { message = "验证码错误或已过期" });
            }

            var result = await _authService.LoginAsync(request);
            if (!result.IsSuccess)
            {
                Console.WriteLine($"Login failed - {result.ErrorMessage}");
                if (result.IsLocked)
                {
                    return StatusCode(423, new { message = result.ErrorMessage }); // 423 Locked
                }
                return Unauthorized(new { message = result.ErrorMessage });
            }

            Console.WriteLine("Login successful");
            return Ok(result.Response);
        }

        /// <summary>
        /// 验证Token有效性
        /// </summary>
        /// <returns>验证结果</returns>
        [HttpPost("validate-token")]
        [Authorize]
        public async Task<ActionResult> ValidateToken()
        {
            try
            {
                // 如果能走到这里，说明Token是有效的
                // 可以返回一些用户信息，但不返回敏感数据
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                var username = User.Identity?.Name;
                
                return await Task.FromResult<ActionResult>(Ok(new 
                { 
                    valid = true,
                    userId = userId,
                    username = username,
                    timestamp = DateTime.UtcNow
                }));
            }
            catch
            {
                return await Task.FromResult<ActionResult>(Unauthorized(new { valid = false, message = "Token无效" }));
            }
        }
    }
}